package com.frxuexi.lib_base.net

import com.frxuexi.lib_base.BaseApp
import java.io.InputStream
import java.security.KeyStore
import java.security.cert.CertificateFactory
import java.util.Arrays
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager


object SSLUtils {
    private var sslSocketFactory: SSLSocketFactory? = null
    private var trustManager: X509TrustManager? = null
    fun getSslSocketFactory(): SSLSocketFactory? {
        return sslSocketFactory
    }

    fun getTrustManager(): X509TrustManager? {
        return trustManager
    }

    init {
        //加载assets下的证书文件
        val certificate: InputStream = BaseApp.context.getAssets().open("httpsKey.cer")
        val certificateFactory = CertificateFactory.getInstance("X.509")
        val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
        //去掉系统默认证书
        //去掉系统默认证书
        keyStore.load(null)

        keyStore.setCertificateEntry("alias", certificateFactory.generateCertificate(certificate))
        if (certificate != null) {
            certificate.close()
        }
        //信任管理器
        val trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)

        val trustManagers = trustManagerFactory.trustManagers
        check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
            "Unexpected default trust managers:" + Arrays.toString(
                trustManagers
            )
        }
        trustManager = trustManagers[0] as X509TrustManager
        //初始化SSLContext
        val sslContext = SSLContext.getInstance("TLS")
        sslContext.init(null, arrayOf<TrustManager>(trustManager!!), null)
        sslSocketFactory = sslContext.socketFactory
    }
}